﻿Imports Lidgren.Network

Enum PacketTypes
    LOGIN
    MOVE
    WORLDSTATE
End Enum

Public Enum ServerCodes
    CMDExit = 1
    CMDStart = 2
    CMDRun = 3
End Enum

Module DanoQuestServer

    Public SleepTimer As Integer = 100
    Public Server As NetServer
    Public Config As NetPeerConfiguration
    Public ServerStatus As ServerCodes = ServerCodes.CMDRun
    Public Incoming As NetIncomingMessage

    Sub Main()
        Config = New NetPeerConfiguration("DanoQuest")
        Config.Port = 14444
        Config.MaximumConnections = 200
        Config.EnableMessageType(NetIncomingMessageType.ConnectionApproval)
        Server = New NetServer(Config)
        Server.Start()
        System.Console.WriteLine("Server Started.")
        While ServerStatus = ServerCodes.CMDRun
            Try
                System.Console.WriteLine("Waiting for new connections...")
                While True
                    Incoming = Server.ReadMessage() ' Server.ReadMessage() Returns new messages, that have not yet been read.
                    If Incoming IsNot Nothing Then
                        Select Case Incoming.MessageType
                            Case NetIncomingMessageType.ConnectionApproval 'TODO: Login initialization
                                If Incoming.ReadByte() = CByte(PacketTypes.LOGIN) Then
                                    Dim PlayerName As String = Incoming.ReadString
                                    System.Console.WriteLine("Incoming LOGIN (" & PlayerName & ")")
                                    Incoming.SenderConnection.Approve()
                                    SendMessage(PacketTypes.LOGIN, True)
                                    System.Console.WriteLine("Approved new connection.")
                                End If
                                Exit Select
                            Case NetIncomingMessageType.Data 'is all messages manually sent from client
                                If Incoming.ReadByte() = CByte(PacketTypes.WORLDSTATE) Then
                                    Dim Mynewstate As String = Incoming.ReadString
                                    System.Console.WriteLine("WORLDSTATE (" & Mynewstate & ")")
                                    'TODO: Check who sent the message 
                                    ' If stored connection ( check approved message. We stored ip+port there, to character obj EX: If ch.Connection IsNot inc.SenderConnection Then
                                End If
                                Exit Select
                            Case NetIncomingMessageType.StatusChanged
                                ' In case status changed
                                ' It can be one of these
                                ' NetConnectionStatus.Connected;
                                ' NetConnectionStatus.Connecting;
                                ' NetConnectionStatus.Disconnected;
                                ' NetConnectionStatus.Disconnecting;
                                ' NetConnectionStatus.None;

                                ' NOTE: Disconnecting and Disconnected are not instant unless client is shutdown with disconnect()
                                Console.WriteLine(Incoming.SenderConnection.ToString() & " status changed. " & Incoming.SenderConnection.Status)
                                If Incoming.SenderConnection.Status = NetConnectionStatus.Disconnected OrElse Incoming.SenderConnection.Status = NetConnectionStatus.Disconnecting Then
                                    Console.WriteLine("DISCONNECTED")
                                End If
                                Exit Select
                            Case Else
                                Console.WriteLine("Not Important Message")
                                Exit Select
                        End Select
                    End If
                    'Update World Logic Here?
                    ' System.Threading.Thread.Sleep(SleepTimer)
                End While
            Catch ex As Exception
                System.Console.WriteLine(ex.ToString)
            End Try
        End While
    End Sub

    Private Sub SendMessage(ByVal PacketType As PacketTypes, Optional ByVal Data As Object = False)
        Dim outmsg As NetOutgoingMessage = Server.CreateMessage()
        outmsg.Write(CByte(PacketType))
        outmsg.Write(Data)
        ' Send message/packet to all connections, in reliably order, channel 0
        ' Reliably means, that each packet arrives in same order they were sent. Its slower than unreliable, but easyest to understand
        Server.SendMessage(outmsg, Incoming.SenderConnection, NetDeliveryMethod.ReliableOrdered, 0)
    End Sub

End Module